import protoRoot from './protocol/proto'
import bus from '../utils/message-bus.js'
import db from '../datastore'

const messageType = {
  LOGIN: 1,
  MESSAGE: 2,
  PING: 3
}
const messageProtocol = protoRoot.lookup('protocol.MessageProtocol')

const ChatController = {
  connect: false,
  requestId: null,
  websocket: null,
  genMessage: function(to, message) {
    // 请求体message
    const messageObject = {
      from: this.requestId,
      to: to,
      createTime: new Date().getTime(),
      content: message,
      type: messageType.MESSAGE
    }
    return messageProtocol.encode(messageProtocol.create(messageObject)).finish()
  },
  login: function() {
    // 请求体message
    const messageObject = {
      from: this.requestId,
      to: this.requestId,
      createTime: new Date().getTime(),
      content: '登录用户：' + this.requestId,
      type: messageType.LOGIN
    }
    const request = messageProtocol.encode(messageProtocol.create(messageObject)).finish()
    if (this.websocket.readyState === WebSocket.OPEN) { // 如果WebSocket是打开状态
      this.websocket.send(request) // send()发送消息
    }
  },
  // 提交聊天消息内容
  submit: function(to, message) {
    if (message !== '') {
      if (this.websocket.readyState === WebSocket.OPEN) { // 如果WebSocket是打开状态
        this.websocket.send(this.genMessage(to, message)) // send()发送消息
      }
    } else {
      console.log('message is null')
    }
    return false
  },
  // 初始化WebSocket连接
  init: async function() {
    const _this = this
    const userInfo = db.read().get('user').value()
    this.requestId = userInfo.userId

    if (!this.requestId) {
      return
    }
    if (this.connect) {
      return
    }
    // 连接websocket服务器
    this.websocket = new WebSocket('ws://localhost:8192/chat')

    // 当有消息过来的时候触发
    this.websocket.onmessage = function(event) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(event.data)
      reader.onload = function() {
        // noinspection JSCheckFunctionSignatures
        const buffer = new Uint8Array(reader.result)
        bus.$emit('receive-message', messageProtocol.decode(buffer))
      }
    }
    // 连接关闭的时候触发
    this.websocket.onclose = function(event) {
      _this.connect = false
      console.log(event)
    }
    // 连接打开的时候触发
    this.websocket.onopen = function() {
      // 告诉服务器端有用户登录
      _this.connect = true
      ChatController.login()
    }
  }
}
export default ChatController
